package com.example.curvedemo.util;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.util.TypedValue;

import androidx.annotation.NonNull;

/**
 * Created by goldze on 2017/5/14.
 * 常用工具类
 */
public final class AppContextUtil {

    @SuppressLint("StaticFieldLeak")
    private static Context context;

    private AppContextUtil() {
        throw new UnsupportedOperationException("u can't instantiate me...");
    }

    /**
     * 初始化工具类
     *
     * @param context 上下文
     */
    public static void init(@NonNull final Context context) {
        AppContextUtil.context = context.getApplicationContext();
    }

    /**
     * 获取ApplicationContext
     *
     * @return ApplicationContext
     */
    public static Context getContext() {
        if (context != null) {
            return context;
        }
        throw new NullPointerException("should be initialized in application");
    }

    public static String getString(int stringId) {
        if (context != null) {
            return context.getResources().getString(stringId);
        }
        return "";
    }

    public static Drawable getDrawable(int drawableId) {
        if (context != null) {
            return context.getResources().getDrawable(drawableId);
        }
        return null;
    }

    /**
     * 根据宽高获取Drawable
     *
     * @param drawableId
     * @param width      宽（单位dp）
     * @param height     高（单位dp）
     * @return
     */
    public static Drawable getDrawable(int drawableId, int width, int height) {
        if (context != null) {
            Drawable drawable = context.getResources().getDrawable(drawableId);
            width = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, width, context.getResources().getDisplayMetrics());
            height = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, height, context.getResources().getDisplayMetrics());
            drawable.setBounds(0, 0, width, height);
            return drawable;
        }
        return null;
    }

    public static int getColor(int colorId) {
        if (context != null) {
            return context.getResources().getColor(colorId);
        }
        return 0;
    }
}